var express = require('express')
var { graphqlHTTP } = require('express-graphql')
const graphql = require('graphql')

var app = express()

var AccountType = new graphql.GraphQLObjectType({
  name: 'Account',
  fields: {
    name: { type: graphql.GraphQLString },
    age: { type: graphql.GraphQLInt },
    sex: { type: graphql.GraphQLString },
    department: { type: graphql.GraphQLString }
  }
})

var queryType = new graphql.GraphQLObjectType({
  name: 'Query',
  fields: {
    account: {
      type: AccountType,
      args: {
        username: { type: graphql.GraphQLString }
      },
      resolve: function(_, { username }) {
        return {
          name: username,
          sex: 'man',
          age: 18,
          department: '开发部',
        }
      }
    }
  }
})

var schema = new graphql.GraphQLSchema({ query: queryType })

app.get('/', (req, res) => {
  res.end(`<a href="/graphql">graphql</a>`)
})

app.post('/cookie', function(req, res) {
  res.json({
    cookie: "cookie"
  })
})

app.use('/graphql', graphqlHTTP({
  schema: schema,
  graphiql: true // 是否开启调试界面，true是开启，false是不开启
}))

app.use(express.static('public'))

app.listen(4000, () => console.log('server is run on http://localhost:4000'))